<template>
  <c-form-dialog
    label-width="140px"
    :title="dialogTitle"
    ref="form"
    class="project-new-form"
    :table-name="formTable"
    :form-items="formItems"
    :form-data="formData"
    :before-save="handleBeforeSave"
    :table-id="tableId"
    :visible.sync="innerVisible"
    @close="handleDismiss"
    :auto-close="false"
    v-on="$listeners"
    :v-loading="loading"
  >
    <span class="validate-result ml-3" slot="appendSlot">
      <i class="fa fa-check text-success"></i>
      <i class="fa fa-times text-danger"></i>
    </span>
    <el-form-item
      label="营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)"
      v-show="isCommon"
      slot="registerAttach"
    >
      <upload-oss
        single-image
        :dir="dir"
        ref="uploadRegister"
        accept="image/*"
        :fileName="0"
        :file-list="registerList"
        :on-change="registerChange"
        :on-complete="handleUploadRegister"
      ></upload-oss>
    </el-form-item>
    <el-form-item
      label="身份证照片OCR识别(请上传清晰的图片，以确保识别准确性，非必填)"
      slot="attach"
      v-show="!isCommon"
    >
      <ul class="list-inline">
        <li class="list-inline-item">
          <upload-oss
            single-image
            :dir="dir"
            ref="uploadFront"
            accept="image/*"
            :fileName="0"
            :file-list="idImgFront"
            :on-change="idImgFrontChange"
            :on-complete="handleUploadFront"
          ></upload-oss>
          <div class="text-muted text-center">身份证头像页</div>
        </li>
        <li class="list-inline-item">
          <upload-oss
            single-image
            :dir="dir"
            ref="uploadBack"
            accept="image/*"
            :file-list="idImgBack"
            :on-complete="handleUploadBack"
          ></upload-oss>
          <div class="text-muted text-center">身份证国徽页</div>
        </li>
      </ul>
    </el-form-item>
  </c-form-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { license18Validate, mul } from '@vimi/utils-tool'
import { idCardValidator, mobileValidator } from '@/common/plugins/validator'
import { enumDispute } from '@/bank/plugins/enum'

import SelectAddress from '@/components/select/SelectAddress'
import SelectProduct from '@/bank/views/limit/SelectProduct'
import SelectParentMain from '@/bank/views/limit/SelectParentMain'
import SelectCustomerType from '@/bank/views/limit/SelectCustomerType'
import {
  getIdCard,
  getOrgInfo,
  ocrDateFormat,
  OCR_LICENSE_PERIOD_LONG,
} from '@/credit/views/city/program/ocr/index'
import { deleteOss } from '@/common/api/oss'
export default {
  components: {},
  props: {
    visible: Boolean,
    tableId: String,
    formData: { type: Object, default: () => ({}) },
    title: String,
  },
  data() {
    const registerNoValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!license18Validate(value)) {
        callback(new Error('错误的统一信用代码，请重新输入'))
      } else {
        callback()
      }
    }

    return {
      registerList: [],
      idImgFront: [],
      idImgBack: [],
      formTable: 'customer_related_quick',
      innerVisible: false,
      orgClass: '',
      formItems: [
        {
          tag: 'input',
          attrs: { key: 'project_type_name' },
          ifShow: false,
        },
        {
          tag: SelectCustomerType,
          itemAttrs: {
            label: '组织类型',
            rules: { required: true, message: '请选择客户类型', trigger: 'change' },
          },
          attrs: { clearable: false, key: 'org_class', class: 'form-control-ml' },
          appendSlot: 'appendSlot',
          events: {
            select: (model, v, label) => {
              this.orgClass = v || ''
              model.org_class_name = label || ''
            },
          },
        },
        {
          itemAttrs: {
            label: '营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)',
          },
          attrs: {
            key: 'register_attachment',
          },
          slot: 'registerAttach',
          ifShow: () => this.isCommon,
        },
        {
          itemAttrs: {
            label: '身份证照片OCR识别(请上传清晰的图片，以确保识别准确性，非必填)',
          },
          attrs: {
            key: 'idcard_attachment',
          },
          slot: 'attach',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '借款人',
            rules: [{ required: true, message: '请输入借款人名称', trigger: 'blur' }],
          },
          attrs: { key: 'customer_name', value: '', placeholder: '请输入借款人名称' },
          appendSlot: 'appendSlot',
        },

        {
          tag: 'input',
          itemAttrs: {
            label: '身份证号码',
            rules: [
              { required: true, message: '请输入身份证号码', trigger: 'blur' },
              { validator: idCardValidator, message: '请输入正确的身份证号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'lender_idcard', value: '', placeholder: '请输入信息' },
          appendSlot: 'appendSlot',
          ifRender: () => !this.isCommon,
          // getItemAttrs: () => {
          //   return this.isCommon
          //     ? {
          //         rules: {
          //           validator: idCardValidator,
          //           message: '请输入正确的身份证号码',
          //           trigger: 'blur',
          //         },
          //       }
          //     : {
          //         rules: [
          //           { required: true, message: '请输入身份证号码', trigger: 'blur' },
          //           {
          //             validator: idCardValidator,
          //             message: '请输入正确的身份证号码',
          //             trigger: 'blur',
          //           },
          //         ],
          //       }
          // },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '身份证证件地址',
          },
          attrs: { key: 'cert_address_corp', value: '', placeholder: '身份证证件地址' },
          appendSlot: 'appendSlot',
          ifRender: () => !this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '统一社会信用代码',
            rules: [
              { required: true, message: '请输入统一信用代码', trigger: 'blur' },
              {
                validator: registerNoValidator,
                message: '请输入正确的统一信用代码',
                trigger: 'blur',
              },
            ],
          },
          attrs: { key: 'register_no', value: '', placeholder: '请输入信息' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '营业执照证件地址',
          },
          attrs: { key: 'cert_address', value: '', placeholder: '营业执照证件地址' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '成立日期',
          },
          attrs: { key: 'established_date', value: '', placeholder: '成立日期' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '负责人姓名',
            rules: [{ required: true, message: '请输入负责人姓名', trigger: 'blur' }],
          },
          attrs: { key: 'corp_name', value: '', placeholder: '负责人姓名' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '注册资本',
          },
          attrs: { key: 'register_funds', value: '', placeholder: '注册资本' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '营业期限',
          },
          attrs: { key: 'business_year', value: '', placeholder: '营业期限' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'textarea',
          itemAttrs: {
            label: '经营范围',
          },
          attrs: { key: 'business_scope', value: '', placeholder: '经营范围' },
          appendSlot: 'appendSlot',
          ifRender: () => this.isCommon,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            rules: [
              { required: true, message: '请输入手机号码', trigger: 'blur' },
              { validator: mobileValidator, message: '请输入正确的手机号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'mobile_no', value: '', placeholder: '联系电话' },
          appendSlot: 'appendSlot',
        },
        {
          tag: SelectAddress,
          itemAttrs: {
            label: '经营地址',
            rules: { required: true, message: '请选择经营地址/联系地址', trigger: 'change' },
          },
          attrs: {
            key: 'address_code',
            value: '',
            placeholder: '请选择经营地址/联系地址',
            class: 'form-control-ml',
            autoTop: true,
          },
        },
        {
          tag: 'radio-group',
          itemAttrs: { label: '是否有自有房产' },
          attrs: { clearable: false, key: 'is_own_house_cert', value: '0', options: enumDispute },
          appendSlot: 'appendSlot',
        },

        {
          tag: 'select',
          itemAttrs: {
            label: '十二大产业',
            rules: [{ required: true, message: '请选择十二大产业', trigger: 'change' }],
          },
          attrs: { clearable: false, key: 'main_business_code' },
          appendSlot: 'appendSlot',
          getAttrs: () => {
            return { options: this.provinceMainBusinessEnum }
          },
        },
        {
          tag: SelectParentMain,
          itemAttrs: {
            label: '所属行业',
            rules: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
          },
          attrs: { clearable: false, key: 'ind_class_code', class: 'form-control-ml' },
          appendSlot: 'appendSlot',
          events: {
            select: (model, value, select) => {
              model.ind_class_name = select.value || ''
            },
          },
        },
        {
          tag: 'input',
          attrs: {
            key: 'ind_class_name',
          },
          ifShow: false,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '主营品种',
          },
          attrs: { key: 'business_category', value: '', placeholder: '请输入主营品种' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '经营规模',
            rules: { required: true, message: '请输入经营规模', trigger: 'blur' },
          },
          attrs: { key: 'plant_area', value: '', placeholder: '请输入经营规模' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '经营年限',
            rules: { required: true, message: '请输入经营年限', trigger: 'blur' },
          },
          attrs: { key: 'plant_year', value: '', placeholder: '请输入经营年限' },
          appendSlot: 'appendSlot',
          tagSlots: [{ name: 'append', slot: '年' }],
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 0,
                max: 200,
              },
            },
          ],
        },

        {
          tag: SelectProduct,
          itemAttrs: {
            label: '贷款产品',
            rules: [{ required: true, message: '请选择贷款产品', trigger: 'change' }],
          },
          attrs: {
            key: 'project_type_id',
            placeholder: '请选择贷款产品',
            class: 'form-control-ml',
            channelType: '1',
            guaType: '4',
          },
          events: {
            select: (model, label) => {
              model.project_type_name = label
            },
          },
        },
        {
          tag: 'radio-group',
          itemAttrs: { label: '征信是否满足方案准入' },
          attrs: { clearable: false, key: 'is_credit_access', value: '1', options: enumDispute },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'upload',
          itemAttrs: {
            label: '征信不满足准入的说明（附件）',
            class: 'form-control-ml',
            rules: [
              { required: true, message: '请上传征信不满足准入的说明（附件）', trigger: 'change' },
            ],
          },
          attrs: {
            key: 'credit_not_access_at',
            value: '',
            placeholder: '征信不满足准入的说明（附件）',
            accept: '',
            listType: '',
            dir: '/bank/credit',
          },
          ifRender: model => +model.is_credit_access === 0,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '授信金额',
            rules: [{ required: true, message: '请输入授信金额', trigger: 'blur' }],
          },
          attrs: { key: 'apply_funds', value: '', placeholder: '请输入授信金额' },
          tagSlots: [{ name: 'append', slot: '万元' }],
          appendSlot: 'appendSlot',
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '贷款用途',
            rules: [{ required: true, message: '请输入贷款用途', trigger: 'blur' }],
          },
          attrs: { clearable: false, key: 'funds_use_dir', placeholder: '请输入贷款用途' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '本次支用金额',
            rules: [{ required: true, message: '请输入本次支用金额', trigger: 'blur' }],
          },
          attrs: { key: 'cur_use_funds', value: '', placeholder: '请输入本次支用金额' },
          appendSlot: 'appendSlot',
          tagSlots: [{ name: 'append', slot: '万元' }],
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '贷款(支用)期限',
            rules: [{ required: true, message: '请输入贷款(支用)期限', trigger: 'blur' }],
          },
          attrs: { key: 'months', value: '', placeholder: '请输入贷款(支用)期限' },
          appendSlot: 'appendSlot',
          tagSlots: [{ name: 'append', slot: '月' }],
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 0,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '已支用余额',
          },
          attrs: { key: 'left_funds', value: '', placeholder: '请输入已支用余额' },
          appendSlot: 'appendSlot',
          tagSlots: [{ name: 'append', slot: '万元' }],
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '贷款利率',
            rules: [{ required: true, message: '请输入贷款利率', trigger: 'blur' }],
          },
          attrs: { key: 'load_rate', value: '', placeholder: '请输入贷款利率' },
          appendSlot: 'appendSlot',
          tagSlots: [{ name: 'append', slot: '%' }],
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
              },
            },
          ],
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '担保费率',
            rules: [{ required: true, message: '请输入担保费率', trigger: 'blur' }],
          },
          attrs: { key: 'gua_rate', value: '', placeholder: '请输入担保费率' },
          appendSlot: 'appendSlot',
          tagSlots: [{ name: 'append', slot: '%' }],
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                fixed: 2,
                max: 100,
              },
            },
          ],
        },
        {
          tag: 'date',
          itemAttrs: {
            label: '借款/授信开始时间',
            rules: [{ required: true, message: '请选择借款/授信开始时间', trigger: 'change' }],
          },
          attrs: { key: 'load_date', value: '', placeholder: '请选择借款/授信开始时间' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'date',
          itemAttrs: {
            label: '借款/授信结束时间',
            rules: [{ required: true, message: '借款/授信结束时间', trigger: 'change' }],
          },
          appendSlot: 'appendSlot',
          attrs: { key: 'load_end_date', value: '', placeholder: '请选择借款/授信结束时间' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '银担协议名称',
            rules: [{ required: true, message: '请输入银担协议名称', trigger: 'blur' }],
          },
          attrs: { clearable: false, key: 'bank_gua_name', placeholder: '请输入银担协议名称' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '银担协议编号',
            rules: [{ required: true, message: '请输入银担协议编号', trigger: 'blur' }],
          },
          attrs: { clearable: false, key: 'bank_gua_no', placeholder: '请输入银担协议编号' },
          appendSlot: 'appendSlot',
        },
        {
          tag: 'date',
          itemAttrs: {
            label: '银担协议签订时间',
            rules: [{ required: true, message: '银担协议签订时间', trigger: 'change' }],
          },
          appendSlot: 'appendSlot',
          attrs: {
            key: 'bank_gua_time',
            value: '',
            placeholder: '银担协议签订时间',
            format: 'yyyy年MM月dd日',
          },
        },
      ],
      mainBusiness: {},
      parentMainBusiness: {},
      cityCode: '',
      loading: false,
      registerfile: null,
      imgData: [],
      attachTable: 'datum_customer_attachment',
      editData: {},
      deleteAttach: [],
    }
  },
  computed: {
    ...mapGetters(['clientId', 'org', 'user', 'userId', 'provinceMainBusinessEnum']),
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    bankType() {
      return this.user.clientOrgClassType
    },
    bankName() {
      return this.org.orgName
    },
    dialogTitle() {
      return this.title || (this.tableId ? '修改项目信息' : '新增项目信息')
    },
    dir() {
      return `/bank/newProjec/limit/fast/${this.clientId}`
    },
    isCommon() {
      return ['org_cooperative', 'org_enterprise'].includes(this.orgClass)
    },
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (val) {
        this.initAttach()
        this.orgClass = this.formData.org_class
        this.formData.bank_gua_time =
          this.formData?.bank_gua_time?.replace('年', '-').replace('月', '-').replace('日', '') ??
          ''
        if (this.tableId) {
          this.toValidate()
        }
      }
    },
  },
  created() {
    this.$store.dispatch('getProvinceMainBusiness')
  },
  mounted() {},
  methods: {
    initAttach() {
      this.registerList = []
      this.idImgFront = []
      this.idImgBack = []
      this.imgData = []
      if (!this.tableId) {
        return
      }
      this.loading = true
      this.$api
        .getData('credit', this.attachTable, {
          'customer_related_id.eq': this.tableId,
          'attachment_type.in': '身份证,营业执照',
        })
        .then(res => {
          const attach = res?.data ?? []
          const customerIdCardFace = attach.find(
            item =>
              item.attachment_type === '身份证' &&
              item.attachment_type_code === 'face' &&
              item.lender_idcard === this.formData.lender_idcard
          )
          if (customerIdCardFace) {
            this.idImgFront = [{ url: customerIdCardFace.attachment, id: customerIdCardFace.id }]
          }
          const customerIdCardBack = attach.find(
            item =>
              item.attachment_type === '身份证' &&
              item.attachment_type_code === 'back' &&
              item.lender_idcard === this.formData.lender_idcard
          )
          if (customerIdCardBack) {
            this.idImgBack = [{ url: customerIdCardBack.attachment, id: customerIdCardBack.id }]
          }
          const customerRegitster = attach.find(
            item =>
              item.attachment_type === '营业执照' &&
              item.lender_idcard === this.formData.register_no
          )
          if (customerRegitster) {
            this.registerList = [{ url: customerRegitster.attachment, id: customerRegitster.id }]
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      this.registerfile = file.raw
      const fileData = file.raw
      this.loading = true
      getOrgInfo(fileData)
        .then(res => {
          const data = res?.data ?? {}
          this.$refs.form.setAttrs('customer_name', { value: data.name || '' })
          this.$refs.form.setAttrs('register_no', { value: data.reg_num || '' })
          this.$refs.form.setAttrs('corp_name', { value: data.person || '' })
          this.$refs.form.setAttrs('cert_address', { value: data.address || '' })
          this.$refs.form.setAttrs('business_scope', { value: data.business || '' })
          this.$refs.form.setAttrs('register_funds', { value: data.capital || '' })
          this.$refs.form.setAttrs('established_date', {
            value: ocrDateFormat(data.establish_date) || '',
          })
          this.$refs.form.setAttrs('business_year', {
            value:
              data.valid_period === OCR_LICENSE_PERIOD_LONG
                ? '长期'
                : `${ocrDateFormat(data.establish_date)}至${ocrDateFormat(data.valid_period)}`,
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    async idImgFrontChange(file) {
      if (!file || !file.raw) {
        return
      }
      const fileData = file.raw
      this.loading = true
      getIdCard(fileData, true)
        .then(res => {
          const data = res?.data ?? {}
          this.$refs.form.setAttrs('lender_idcard', { value: data.num || '' })
          this.$refs.form.setAttrs('corp_name', { value: data.name || '' })
          this.$refs.form.setAttrs('cert_address_corp', { value: data.address || '' })
          if (!this.isCommon) {
            this.$refs.form.setAttrs('customer_name', { value: data.name || '' })
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    toValidate() {
      this.$nextTick(() => {
        const cfrom = this.$refs.form
        const form = cfrom.$refs.cForm.$refs.form
        form.validate(() => {})
      })
    },
    async handleBeforeSave(model) {
      // model.org_class_name = enumCustomerType[model.org_class]
      model.address_code = model.address_code || this.queryAddressCode
      model.bank_id = this.clientId
      model.bank_name = this.bankName
      model.bank_type = this.bankType
      if (!this.formData.bank_user_id) {
        model.bank_user_id = this.userId
        model.bank_user_name = this.user.realName
      }

      const year = Math.ceil(model.months / 12)
      model.gua_fee = mul(model.cur_use_funds, model.gua_rate, year, 100)
      model.channel_claim_status = 1
      model.claim_status = 1
      model.submit_type = 5
      model.gua_type = 4
      model.main_business = this.provinceMainBusinessEnum[model.main_business_code]
      model.bank_gua_time = this.$utils.dateFormat(model.bank_gua_time, 'yyyy年MM月dd日')
      this.editData = { ...model }
      this.loading = true
      await this.$refs.uploadRegister?.submit()
    },
    handleUploadAttach(img, fileUrl, type = '身份证', isFase = true, id, fileName = '') {
      if (img.url && img.url !== fileUrl.url) {
        const data = {
          attachment: img.url,
          attachment_type: type,
          parent_attachment_type: '立项附件',
          attachment_type_code: isFase ? 'face' : 'back',
          lender_idcard: id,
          remark: fileName || img.name,
        }
        if (this.tableId) {
          data.customer_related_id = this.tableId
        }
        if (fileUrl && fileUrl.id) {
          data.id = fileUrl.id
        }
        this.imgData.push(data)
        if (fileUrl.id) {
          this.deleteAttach.push(fileUrl)
        }
      }
    },
    async handleUploadRegister(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.registerList?.[0] || {}
      this.handleUploadAttach(img, fileUrl, '营业执照', true, this.editData.register_no, '')
      await this.$refs.uploadFront?.submit()
    },
    async handleUploadFront(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.idImgFront?.[0] || {}
      const name = this.isCommon
        ? `身份证(头像页)-${this.editData.corp_name}`
        : `身份证(头像页)-${this.editData.customer_name}`
      this.handleUploadAttach(img, fileUrl, '身份证', true, this.editData.lender_idcard, name)
      await this.$refs.uploadBack?.submit()
    },
    async handleUploadBack(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.idImgBack?.[0] || {}
      const name = this.isCommon
        ? `身份证(国徽页)-${this.editData.corp_name}`
        : `身份证(国徽页)-${this.editData.customer_name}`
      this.handleUploadAttach(img, fileUrl, '身份证', false, this.editData.lender_idcard, name)
      await this.onSubmit()
    },
    async onSubmit() {
      const formData = {
        masterTableInfo: JSON.stringify(this.editData),
        masterTableName: this.formTable,
        slaveTableName: this.attachTable,
        slaveTableInfo: JSON.stringify(this.imgData),
      }
      if (!this.tableId) {
        await this.addFarm(formData)
      } else {
        // 修改需传所有附件不然会删除，所以单独添加附件
        await this.$api
          .updateData(this.$serviceName, this.formTable, this.tableId, this.editData)
          .then(() => {
            this.$message.success('修改成功！')
            this.handleDismiss()
            this.$emit('success', true)
          })
          .finally(() => {
            this.loading = false
          })
        this.submitAttachment()
      }
      this.deleteAttachMent()
    },
    deleteAttachMent() {
      if (!this.deleteAttach.length) {
        return
      }
      // const ids = this.deleteAttach.map(item => item.id).join(',')
      // 组件自带删除fileList oss文件
      const urls = this.deleteAttach.map(item => item.url)
      // this.$api.deleteData(this.$serviceName, this.attachTable, ids)
      deleteOss(urls)
      this.deleteAttach = []
    },
    submitAttachment() {
      if (this.imgData.length > 0) {
        this.$api.updateBatch('credit', 'datum_customer_attachment', this.imgData)
      }
    },
    addFarm(data) {
      return this.$api
        .relatedBatch(this.$serviceName, data)
        .then(() => {
          this.$message.success('添加客户成功！')
          this.handleDismiss()
          this.$emit('success', true)
        })
        .catch(err => {
          if (err) {
            const errStr = typeof err.data === 'string' ? err.data : '添加客户失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDismiss() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.project-new-form {
  .validate-result {
    display: none;
  }
  .is-success {
    .validate-result {
      display: inline-block;
      .fa-times {
        display: none;
      }
    }
  }
  .is-error {
    .validate-result {
      display: inline-block;
      .fa-check {
        display: none;
      }
    }
  }
}
</style>
